package com.kuaimacode.kframework.web.controller;

import com.kuaimacode.kframework.common.Constant;
import com.kuaimacode.kframework.common.JsonResult;
import com.kuaimacode.kframework.component.ComponentUtil;
import com.kuaimacode.kframework.component.SmsRecordService;
import com.kuaimacode.kframework.component.SmsSendService;
import com.kuaimacode.kframework.exception.ErrorEnum;
import com.kuaimacode.kframework.exception.ServerInternalErrorException;
import com.kuaimacode.kframework.mybatis.models.coupon.CouponInfo;
import com.kuaimacode.kframework.mybatis.models.coupon.UserCoupon;
import com.kuaimacode.kframework.mybatis.models.invite.Invite;
import com.kuaimacode.kframework.mybatis.models.user.User;
import com.kuaimacode.kframework.mybatis.models.user.UserInvite;
import com.kuaimacode.kframework.service.UserInviteService;
import com.kuaimacode.kframework.util.ValidUtil;
import com.kuaimacode.kframework.web.service.*;
import com.kuaimacode.kframework.web.vo.request.CheckValidCodeReq;
import io.swagger.annotations.ApiOperation;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Date;
import java.util.stream.Stream;

@Controller
@RequestMapping("/")
public class IndexController {
    private static String PAGE_FILE_NAME = "index/";
    @Autowired
    private UserService userService;
    @Autowired
    private InviteService inviteService;
    @Autowired
    private SmsSendService smsSendService;
    @Autowired
    private SmsRecordService smsRecordService;
    @Autowired
    private UserInviteService userInviteService;

    @Autowired
    private CouponInfoService couponInfoService;

    @Autowired
    private  UserCouponService userCouponServic;

    @Autowired
    private SysParamService sysParamService;

    @Autowired
    private IndexService indexService;

    @Autowired
    private ComponentUtil componentUtil;

    @Value("${invite.normal.url}")
    private String url;

    @ApiOperation(value = "获取服务器时间")
    @GetMapping("/time")
    public ResponseEntity<?> getTime(){
        return ResponseEntity.status(HttpStatus.OK).body(new Date());
    }

    /**
     * 进入邀请页面
     * @param id
     * @param uid
     * @param map
     * @return
     */
    @RequestMapping(value = "/invite/{id}", method = RequestMethod.GET)
    public String invite(@PathVariable Long id, @RequestParam Long uid,  ModelMap map) {
        Invite invite = inviteService.queryAvailableOne(id);
        String page = PAGE_FILE_NAME+"invite";
        if(invite == null){
            page = PAGE_FILE_NAME+"no_data";
        }else{
            CloseableHttpClient client =null;
            try {
                client =   HttpClients.createDefault();
                String newUrl = String.format(url,invite.getId())+uid;
                String  surl ="http://qr.liantu.com/api.php?&w=300&text="+newUrl;
                String imgUrl = indexService.httpGetImg(client,surl," ");
                map.put("imgUrl", componentUtil.convertImgUrl(imgUrl));
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                if(client!=null){
                    try {
                        client.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            String iosDownloadUrl = sysParamService.findByNameAndAgent("IOS_DOWNLOAD_URL", Constant.DEFAULT_AGENT_ID);
            String androidDownloadUrl = sysParamService.findByNameAndAgent("ANDROID_DOWNLOAD_URL",Constant.DEFAULT_AGENT_ID);
            //User user = userService.getById(uid);
            map.put("uid", uid);
            map.put("invite", invite);
            map.put("iosDownloadUrl", iosDownloadUrl);
            map.put("androidDownloadUrl", androidDownloadUrl);
        }
        return page;
    }

    @ApiOperation(value = "发送验证码")
    @PostMapping("/sendVerifyCode")
    @ResponseBody
    public JsonResult sendVerifyCode(@RequestParam(required = false) String mobile) {
        if (!ValidUtil.isMobile(mobile)) {
            throw new ServerInternalErrorException(ErrorEnum.MOBILE_ERROR);
        }
        //发送验证码
        if (smsSendService.sendLoginVerifyCode(mobile)) {
            return JsonResult.success();
        } else {
            return JsonResult.failure(ErrorEnum.VERIFY_CODE_SEND_ERROR.getCode(),
                    ErrorEnum.VERIFY_CODE_SEND_ERROR.getMsg());
        }
    }

    @ApiOperation(value = "校验验证码是否正确", notes = "校验验证码是否正确，正确发放优惠券")
    @PostMapping("/checkValidCode")
    @ResponseBody
    public JsonResult checkValidCode(@Valid CheckValidCodeReq validCodeReq, @RequestParam(required = false) Long id, @RequestParam(required = false) Long uid) {
        if (smsRecordService.validVerifyCode(validCodeReq.getPhone(), validCodeReq.getVerifyCode())) {
            if(id == null){
                return JsonResult.failure("未找到活动");
            }
            Invite invite = inviteService.queryAvailableOne(id);
            if(invite == null){
                return JsonResult.failure("未找到活动");
            }
            //非绑定手机号场景，如果已存在手机号则登陆成功，不存在则新增账号
            User user = userService.selectByPhone(validCodeReq.getPhone());
            if (user == null) {
                user = new User();
                user.setUsername(validCodeReq.getPhone());
                user.setPhone(validCodeReq.getPhone());
                user.setEnabled(1);
                user.setIsProtocol((short) 1);
                userService.add(user);
            }else{
                return JsonResult.failure("您已经是【阿四服务】app的用户");
            }
            //记录邀请记录
            UserInvite userInvite = new UserInvite();
            userInvite.setInviteId(invite.getId());//活动id
            userInvite.setInvitePhone(user.getPhone());
            userInvite.setInviteTime(new Date());
            userInvite.setInviteUserId(user.getId());//被邀请人
            userInvite.setReward(invite.getSubTitle());
            userInvite.setInviter(uid);//邀请人
            userInviteService.save(userInvite);//保存邀请记录

            final UserCouponService ucs = userCouponServic;
            if(invite.getCoupons() != null && !invite.getCoupons().isEmpty()){
                final Long intiveUserId = user.getId();
                //发放被邀请人优惠券
                String[] array = invite.getCoupons().split(",");
                Stream.of(array).filter(co->co != null && !co.isEmpty()).forEach(co->{
                    //是否过滤已过期 TODO
                    CouponInfo couponInfo = couponInfoService.getById(co);
                    if(couponInfo != null) {
                        UserCoupon userCoupon = new UserCoupon();
                        userCoupon.setState(0);
                        userCoupon.setUseScope(couponInfo.getUseScope() + "");
                        userCoupon.setAmount(couponInfo.getAmount());
                        userCoupon.setCouponId(couponInfo.getId());
                        userCoupon.setType(couponInfo.getType());
                        userCoupon.setDesc(couponInfo.getDescs());
                        //userCoupon.setUseScopeChildType();
                        userCoupon.setUserId(intiveUserId);
                        userCoupon.setMinGoodsAmount(couponInfo.getMinGoodsAmount());
                        userCoupon.setStartTime(couponInfo.getUseStartTime());
                        userCoupon.setEndTime(couponInfo.getUseEndTime());
                        userCoupon.setName(couponInfo.getName());
                        userCoupon.setUseScopeDesc("");//TODO
                        userCoupon.setCreateAt(new Date());
                        userCoupon.setCreateBy(0L);//TODO
                        ucs.save(userCoupon);
                    }
                });
            }
            User inviter = userService.getById(uid);
            if(invite.getInviteCoupons() != null && !invite.getInviteCoupons().isEmpty()){
                final Long intiveId = inviter.getId();
                //发放邀请人优惠券
                if(user != null){
                    String[] array = invite.getInviteCoupons().split(",");
                    Stream.of(array).filter(co->co != null && !co.isEmpty()).forEach(co->{
                        //是否过滤已过期 TODO
                        CouponInfo couponInfo = couponInfoService.getById(co);
                        if(couponInfo != null) {
                            UserCoupon userCoupon = new UserCoupon();
                            userCoupon.setState(0);
                            userCoupon.setUseScope(couponInfo.getUseScope() + "");
                            userCoupon.setAmount(couponInfo.getAmount());
                            userCoupon.setCouponId(couponInfo.getId());
                            userCoupon.setType(couponInfo.getType());
                            userCoupon.setDesc(couponInfo.getDescs());
                            //userCoupon.setUseScopeChildType();
                            userCoupon.setUserId(intiveId);
                            userCoupon.setMinGoodsAmount(couponInfo.getMinGoodsAmount());
                            userCoupon.setStartTime(couponInfo.getUseStartTime());
                            userCoupon.setEndTime(couponInfo.getUseEndTime());
                            userCoupon.setName(couponInfo.getName());
                            userCoupon.setUseScopeDesc("");//TODO
                            userCoupon.setCreateAt(new Date());
                            userCoupon.setCreateBy(0L);//TODO
                            ucs.save(userCoupon);
                        }
                    });
                }
            }
            return JsonResult.success();
        } else {
            return JsonResult.failure(ErrorEnum.VERIFY_CODE_VALID_ERROR.getCode(),
                    ErrorEnum.VERIFY_CODE_VALID_ERROR.getMsg());
        }
    }
}
